from . import db
from werkzeug.security import generate_password_hash, check_password_hash
from datetime import datetime
import json

class User(db.Model):
    __tablename__ = 'users'
    
    id = db.Column(db.Integer, primary_key=True)
    # 用户认证信息
    username = db.Column(db.String(80), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)
    password_hash = db.Column(db.String(255), nullable=False)
    role = db.Column(db.String(20), nullable=False, default='user')  # admin, manager, user
    is_active = db.Column(db.Boolean, default=True)
    
    # 人员详细信息
    name = db.Column(db.String(100), nullable=False)  # 真实姓名
    employee_id = db.Column(db.String(50), unique=True, nullable=False)  # 工号（必填）
    phone = db.Column(db.String(20), nullable=False)  # 电话（必填）
    position = db.Column(db.String(100), nullable=False)  # 职位（必填）
    department = db.Column(db.String(100), nullable=False)  # 部门（必填）
    skills = db.Column(db.Text, nullable=True)  # JSON格式存储技能列表
    
    # 新增必填字段
    area_id = db.Column(db.Integer, db.ForeignKey('areas.id'), nullable=True)  # 区域ID
    id_card = db.Column(db.String(18), unique=True, nullable=False)  # 身份证
    ethnicity = db.Column(db.String(50), nullable=False)  # 民族
    gender = db.Column(db.String(10), nullable=False)  # 性别
    hire_date = db.Column(db.Date, nullable=False)  # 入职时间
    is_driver = db.Column(db.Boolean, nullable=False, default=False)  # 是否驾驶员
    
    # 新增可选字段
    password_field = db.Column(db.String(255), nullable=True)  # 密码字段（用于显示，实际存储在password_hash）
    status = db.Column(db.String(20), nullable=True, default='active')  # 状态
    resignation_date = db.Column(db.Date, nullable=True)  # 离职时间
    electrician_cert_expiry = db.Column(db.Date, nullable=True)  # 电工证有效时间
    height_cert_expiry = db.Column(db.Date, nullable=True)  # 登高证有效时间
    batch_number = db.Column(db.String(50), nullable=True)  # 批号
    remarks = db.Column(db.Text, nullable=True)  # 备注
    
    # 时间戳
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    
    # 关联关系
    group_id = db.Column(db.Integer, db.ForeignKey('groups.id'), nullable=True)
    group = db.relationship('Group', backref='users')
    area = db.relationship('Area', back_populates='members', foreign_keys=[area_id])
    led_areas = db.relationship('Area', back_populates='leader', foreign_keys='Area.leader_id')
    
    # 多对多关系：用户可以关联多个区域
    areas = db.relationship('Area', secondary='user_areas', backref='assigned_users', lazy='dynamic')
    
    def set_password(self, password):
        """设置密码"""
        self.password_hash = generate_password_hash(password)
    
    def check_password(self, password):
        """验证密码"""
        return check_password_hash(self.password_hash, password)
    
    def get_skills_list(self):
        """获取技能列表"""
        if self.skills:
            try:
                return json.loads(self.skills)
            except (json.JSONDecodeError, TypeError):
                return []
        return []
    
    def set_skills_list(self, skills_list):
        """设置技能列表"""
        if isinstance(skills_list, list):
            self.skills = json.dumps(skills_list, ensure_ascii=False)
        else:
            self.skills = None
    

    
    def to_dict(self):
        """转换为字典"""
        # 获取多区域信息
        user_areas = list(self.areas.all())
        area_names = [area.name for area in user_areas]
        area_ids = [area.id for area in user_areas]
        
        return {
            'id': self.id,
            'username': self.username,
            'email': self.email,
            'role': self.role,
            'is_active': self.is_active,
            'name': self.name,
            'employee_id': self.employee_id,
            'phone': self.phone,
            'position': self.position,
            'department': self.department,
            'skills': self.get_skills_list(),
            'group_id': self.group_id,
            'group_name': self.group.name if self.group else None,
            'area_id': self.area_id,  # 保持向后兼容
            'area_name': self.area.name if self.area else None,  # 保持向后兼容
            'areas': area_names,  # 新增：多区域名称列表
            'area_ids': area_ids,  # 新增：多区域ID列表
            'id_card': self.id_card,
            'ethnicity': self.ethnicity,
            'gender': self.gender,
            'hire_date': self.hire_date.isoformat() if self.hire_date else None,
            'is_driver': self.is_driver,
            'password_field': self.password_field,
            'status': self.status,
            'resignation_date': self.resignation_date.isoformat() if self.resignation_date else None,
            'electrician_cert_expiry': self.electrician_cert_expiry.isoformat() if self.electrician_cert_expiry else None,
            'height_cert_expiry': self.height_cert_expiry.isoformat() if self.height_cert_expiry else None,
            'batch_number': self.batch_number,
            'remarks': self.remarks,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None
        }
    

    
    def __repr__(self):
        return f'<User {self.username} ({self.name})>'
